package com.fili.core.storage;

import com.fili.core.serial.SerialConsumer;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by Claudiu-Florin FILIMON
 * Date: Oct 14, 2006
 * Time: 12:11:39 PM
 */
public class StorageContainer
{
    private String fileName;
    private ArrayList<StorageItem> items;
    private ObjectOutputStream objOutStream;


    public StorageContainer(String fileName)
    {
        this.fileName = fileName;
        items = new ArrayList<StorageItem>();

        try
        {
            File f = new File(fileName);
            f.createNewFile();

            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
            readAllFromStream(ois);

            objOutStream = new ObjectOutputStream(new FileOutputStream(fileName, true));
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public void addItem(StorageItem item)
    {
        saveItemToStream(item,objOutStream);
    }

    private StorageItem[] convertToArray(ArrayList<StorageItem> list)
    {
        if (list == null)
            return new StorageItem[0];

        StorageItem[] res = new StorageItem[list.size()];

        for (int i = 0; i < res.length; i++)
            res[i] = list.get(i);

        return res;
    }

    public StorageItem[] getAllItems()
    {
        return convertToArray(items);
    }

    public StorageItem[] filterItems(Date fromDate)
    {
        return convertToArray(items);
    }

    public StorageItem[] filterItems(Date fromDate, Date toDate)
    {
        return convertToArray(items);
    }


    private void readAllFromStream(ObjectInputStream ois)
    {
        items.clear();

        try
        {
            ois.reset();
            while (ois.available() > 0)
            {
                StorageItem item = (StorageItem) ois.readObject();
                items.add(item);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (ClassNotFoundException e)
        {
            e.printStackTrace();
        }
    }

    private void saveAllToStream(ObjectOutputStream oos)
    {

    }

    private void saveItemToStream(StorageItem item, ObjectOutputStream oos)
    {

    }
}
